<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles">添加角色</el-button>
          <el-dialog title="添加角色" :visible.sync="addRolesDialog" width="40%">
            <!-- 添加角色表单 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addForm.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addForm.roleDesc"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addRolesDialog = false">取 消</el-button>
              <el-button type="primary" @click="addRolesBtn">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <!-- 角色信息列表 -->
      <el-table border stripe :data="rolesList">
        <!-- 折叠栏 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['borderBottom',i1===0? 'borderTop':'','evCenter']" v-for="(item1,i1) in scope.row.children"
              :key="item1.id">
              <!-- 一级标签显示 -->
              <el-col :span="5">
                <el-tag closable @close="removeRoles(scope.row,item1.id)">{{item1.authName}}</el-tag>
              </el-col>
              <!-- 二级和三级标签显示 -->
              <el-col :span="19">
                <el-row :class="[i2===0?'':'borderTop','evCenter']" v-for="(item2,i2) in item1.children"
                  :key="item2.id">
                  <!-- 二级显示 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRoles(scope.row,item2.id)">{{item2.authName}}</el-tag>
                  </el-col>
                  <!-- 三级显示 -->
                  <el-col :span="18">
                    <el-tag closable @close="removeRoles(scope.row,item3.id)" type="warning"
                      v-for="(item3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
             {{scope.row}}
            </pre> -->
          </template>
        </el-table-column>
        <!-- 索引栏 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色管理" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="editRolesBtn(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteRolesBtn(scope.row.id)">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showRolesDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- tree结构 -->
    <el-dialog title="分配权限" :visible.sync="isDialogRolesShow" width="40%" @close="setDialogClosed">
      <!-- 树结构 -->
      <el-tree ref="setRightsRef" show-checkbox default-expand-all :default-checked-keys='defaultRoles' node-key="id"
        :data="allotRoulesList" :props="defaultProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogRolesShow = false">取 消</el-button>
        <el-button type="primary" @click="setRights()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色dialog -->
    <el-dialog title="修改角色" :visible.sync="editRolesDialog" width="40%">
      <!-- 添加角色表单 -->
      <el-form :model="editRulesForm" :rules="addFormRules" ref="editRulesFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRulesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRulesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRolesFormBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data: function () {
    return {
      rolesList: [],
      isDialogRolesShow: false,
      allotRoulesList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      defaultRoles: [],
      roleId: '',
      // 显示添加角色弹框
      addRolesDialog: false,
      // 添加角色表单数据源
      addForm: {},
      // 添加角色表单数据验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ]
      },
      // 修改数据的数据源文件
      editRulesForm: {},
      editRolesDialog: false
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色数据失败')
      this.rolesList = res.data
    },
    async removeRoles (roles, id) {
      const info = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (info !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete(`roles/${roles.id}/rights/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      roles.children = res.data
    },
    async showRolesDialog (rowRoles) {
      this.roleId = rowRoles.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return
      this.allotRoulesList = res.data
      // 存入默认的打开的值
      this.recursionRoles(rowRoles, this.defaultRoles)
      this.isDialogRolesShow = true
    },
    recursionRoles (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      // 你有children属性，
      node.children.forEach(item => {
        this.recursionRoles(item, arr)
      })
    },
    setDialogClosed () {
      this.defaultRoles = []
    },
    async setRights () {
      const rids = [
        ...this.$refs.setRightsRef.getCheckedKeys(),
        ...this.$refs.setRightsRef.getHalfCheckedKeys()
      ]
      const ridsStr = rids.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: ridsStr
      })
      if (res.meta.status !== 200) return this.$message.error('修改权限失败')
      this.$message.success('修改权限成功')
      this.getRolesList()
      this.isDialogRolesShow = false
    },
    // 添加角色
    addRoles () {
      this.addRolesDialog = true
    },
    // 添加角色确认按钮
    async addRolesBtn () {
      const { data: res } = await this.$http.post('roles', {
        roleName: this.addForm.roleName,
        roleDesc: this.addForm.roleDesc
      })
      console.log(res)
      if (res.meta.status !== 201) { return this.$message.error('添加角色失败') }
      this.$message.success('添加用户成功')
      this.getRolesList()
      this.addRolesDialog = false
    },
    // 修改角色信息
    async editRolesBtn (roles) {
      const { data: res } = await this.$http.get('roles/' + roles.id)
      if (res.meta.status !== 200) return this.$message.error('修改用户失败')
      this.editRulesForm = res.data
      this.editRolesDialog = true
    },
    // 修改角色信息,送往数据库,渲染页面
    async editRolesFormBtn () {
      const { data: res } = await this.$http.put('roles/' + this.editRulesForm.roleId, {
        roleName: this.editRulesForm.roleName,
        roleDesc: this.editRulesForm.roleDesc
      })
      if (res.meta.status !== 200) return this.$message.error('修改用户失败')
      this.getRolesList()
      this.$message.success('修改角色成功')
      this.editRolesDialog = false
    },
    // 删除角色
    async deleteRolesBtn (id) {
      const confirm = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirm !== 'confirm') return this.$message.info('取消删除成功')
      // 这里就是你真的不要我了,像删我
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      this.getRolesList()
    }
  }
}
</script>
<style lang="less" scoped>
  .borderTop{
    border-top: 1px solid #eeeeee;
  }
  .borderBottom{
    border-bottom: 1px solid #eeeeee;
  }
  .el-tag{
    margin: 7px;
  }
  .evCenter{
    display: flex;
    align-items: center;
  }
</style>
